/*
 * Copyright 2025 The JA-SIG Collaborative. All rights reserved.
 * distributed with this file and available online at
 */
package com.lap.auth.application.menu;

import com.lap.auth.application.menu.assembler.MenuAssembler;
import com.lap.auth.application.menu.command.CreateMenuCmd;
import com.lap.auth.application.menu.command.UpdateMenuCmd;
import com.lap.auth.application.menu.dto.MenuNodeDto;
import com.lap.auth.domain.menu.Menu;
import com.lap.auth.domain.menu.repository.MenuRepository;
import com.lap.auth.domain.menu.service.MenuValidator;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * 菜单应用服务层
 *
 * <ol>
 *   <li>不做业务规则，只做技术规则（加密/解密是技术实现，业务不关注）
 *   <li>取数，赋值，对象转换在这层执行
 *   <li>命名有规范，动词+领域名字
 *   <li>如查询比较多，建议分开领域QueryAppService,如:分页查询，分页查询返回关联字段
 * </ol>
 */
@RequiredArgsConstructor
@Service
public class MenuAppService {

  private final MenuAssembler menuAssembler;
  private final MenuValidator menuValidator;
  private final MenuRepository menuRepository;

  public List<MenuNodeDto> getMenuTree() {
    List<Menu> all = menuRepository.findList();
    List<MenuNodeDto> flatList = menuAssembler.toDtoList(all);
    return menuAssembler.convertToTree(flatList);
  }

  public Integer createMenu(CreateMenuCmd cmd) {
    Menu menu = menuAssembler.toDomain(cmd);
    Menu parentMenu = menuValidator.assertMenuExists(menu.getParentId());
    parentMenu.canCreateChild();
    return menuRepository.save(menu);
  }

  public void updateMenu(Integer id, UpdateMenuCmd cmd) {
    Menu origin = menuValidator.assertMenuExists(id);
    Menu menu = menuAssembler.toDomain(id, cmd);
    List<Menu> child = menuRepository.findByPid(menu.getId());
    menu.assertCanChangeMenuType(origin.getMenuType(), child);
    menuRepository.save(menu);
  }

  public void deleteMenu(Integer id) {
    Menu menu = menuValidator.assertMenuExists(id);
    List<Menu> child = menuRepository.findByPid(id);
    menu.canDelete(child);
    menuRepository.deleteById(id);
  }
}
